package com.daluzy.chmanager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cazaea.sweetalert.SweetAlertDialog;
import com.daluzy.chmanager.R;
import com.daluzy.chmanager.bean.Account;
import com.daluzy.chmanager.bean.Manager;
import com.daluzy.chmanager.bean.School;
import com.daluzy.chmanager.util.TelephoneUtil;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 添加管理员
 */
public class AddManagerActivity extends AppCompatActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_manager_name)
    EditText etManagerName;
    @BindView(R.id.et_manager_phone)
    EditText etManagerPhone;
    @BindView(R.id.tv_manager_school)
    TextView tvManagerSchool;
    @BindView(R.id.tv_add_commit)
    TextView tvAddCommit;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    private String managerName;
    private String managerPhone;
    private School school;

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_manager_daluzy);
        ButterKnife.bind(this);

        loadingDialog = new LoadingDialog(this);
    }

    @OnClick({R.id.iv_back, R.id.tv_manager_school, R.id.tv_add_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_manager_school:
                Intent intent = new Intent(AddManagerActivity.this, SelectSchoolActivity.class);
                startActivityForResult(intent, 2021);
                break;
            case R.id.tv_add_commit:
                tvAddCommit.setEnabled(false);
                check();
                break;
        }
    }

    private void check() {
        managerName = etManagerName.getText().toString().trim();
        managerPhone = etManagerPhone.getText().toString().trim();
        if (TextUtils.isEmpty(managerName)) {
            Toast.makeText(AddManagerActivity.this, "请输入管理员姓名", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(managerPhone)) {
            Toast.makeText(AddManagerActivity.this, "请输入管理员手机号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (!TelephoneUtil.checkCellphone(managerPhone)) {
            Toast.makeText(AddManagerActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        checkAccount();
    }

    private void checkAccount() {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<Account> query = new BmobQuery<>();
        query.addWhereEqualTo("account", managerPhone);
        query.order("-createdAt")
                .findObjects(new FindListener<Account>() {
                    @Override
                    public void done(List<Account> object, BmobException e) {
                        if (e == null) {
                            if (object != null && object.size() > 0) {
                                final SweetAlertDialog mDialog = new SweetAlertDialog(AddManagerActivity.this, SweetAlertDialog.NORMAL_TYPE)
                                        .setTitleText("提示")
                                        .setContentText("该账号已存在，是否直接绑定？")
                                        .setCustomImage(null)
                                        .setCancelText("否")
                                        .setConfirmText("是")
                                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                if (loadingDialog != null)
                                                    loadingDialog.close();
                                            }
                                        }).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                addManager();
                                            }
                                        });
                                mDialog.show();
                            } else {
                                addAccount();
                            }

                        } else {
                            Toast.makeText(AddManagerActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            if (loadingDialog != null)
                                loadingDialog.close();
                        }
                        tvAddCommit.setEnabled(true);
                    }
                });
    }

    private void addAccount(){
        Account account = new Account();
        account.setAccount(managerPhone);
        account.setPassword("123456");
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    addManager();
                } else {
                    Toast.makeText(AddManagerActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    if (loadingDialog != null)
                        loadingDialog.close();
                }

            }
        });
    }

    private void addManager() {
        Manager manager = new Manager();
        manager.setAccount(managerPhone);
        manager.setManager_id(String.valueOf(System.currentTimeMillis()));
        manager.setManager_name(managerName);
        manager.setManager_phone(managerPhone);
        if (school != null) {
            manager.setSchool_id(school.getSchool_id());
            manager.setSchool_name(school.getSchool_name());
        }

        manager.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Toast.makeText(AddManagerActivity.this,"添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(AddManagerActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2021 && resultCode == 2021) {
            school = (School) data.getSerializableExtra("school");
            if (school != null)
                tvManagerSchool.setText(school.getSchool_name());
        }
    }
}
